package com.cly.order.listener;

import com.cly.api.clients.PayClient;
import com.cly.common.entity.order.dto.OrderDetailDto;
import com.cly.common.entity.order.po.Order;
import com.cly.common.entity.pay.po.PayOrder;
import com.cly.order.constants.MqConstant;
import com.cly.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final PayClient payClient;
    private final OrderService  orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstant.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Map<String, Object> data){
        Long orderId = (Long) data.get("orderId");
        List<OrderDetailDto> orderDetails = (List<OrderDetailDto>) data.get("orderDetails");
        // 检查当前订单是否未支付
        Order order = orderService.getById(orderId);
        if(order == null || order.getStatus() != 1){
            // 说明该订单不存在，或者不是未支付
            return;
        }
        // 查询该订单所属的支付订是否为未支付
        PayOrder payOrder = payClient.getPayOrderByOrderIdToOrder(orderId);
        if(payOrder != null || payOrder.getStatus() == 3){
            // 说明该订单存在且是已支付
            // 标记订单为已支付
            orderService.updateOrderStatus(orderId, 2);
        }else {
            // 订单未支付，修改订单状态为取消并恢复库存
            orderService.cancelOrder(orderId, orderDetails);
        }
    }
}
